package com.lw.service.impl;


import com.baidu.aip.util.Base64Util;
import com.lw.mapper.UserMapper;
import com.lw.system.User;
import com.lw.system.response.FaceLoginResult;
import com.lw.system.response.QRCode;
import com.lw.utils.BaiduAiUtil;
import com.lw.utils.IdWorker;
import com.lw.utils.QRCodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class FaceLoginService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private QRCodeUtil qrCodeUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BaiduAiUtil baiduAiUtil;
    @Autowired
    private UserMapper userMapper;
    @Value("${qr.url}")
    private String url;

	//创建二维码
    public QRCode getQRCode() throws Exception {
        //1.获取唯一标志
        String code=idWorker.nextId()+"";
        //2.生成二维码
        String content=url+"?code="+code;
        String qrCode = qrCodeUtil.crateQRCode( content );
        //3.存入当前二维码状态
        FaceLoginResult result=new FaceLoginResult( "-1" );
        redisTemplate.boundValueOps( getCacheKey( code ) ).set( result,10, TimeUnit.MINUTES );//状态对象，失效时间，单位
		return new QRCode( code, qrCode);
    }

	//根据唯一标识，查询用户是否登录成功
    public FaceLoginResult checkQRCode(String code) {
		String key=getCacheKey( code );
        FaceLoginResult faceLoginResult = (FaceLoginResult) redisTemplate.opsForValue().get( key );
        return faceLoginResult;
    }

	//扫描二维码之后，使用拍摄照片进行登录
    //返回用户id
    public String loginByFace(String code, MultipartFile attachment) throws Exception {
        //1.调用百度云Al查询当前用户
        String userId = baiduAiUtil.faceSearch( Base64Util.encode( attachment.getBytes() ) );
        //2.自动登录（token）
        FaceLoginResult result=new FaceLoginResult( "0" );
        if (userId!=null){
            //自已模拟登录
            //查询用户
            User user=userMapper.findById( userId );
            if (user!=null) {
                //获取subject
                Subject subject = SecurityUtils.getSubject();
                //调用login方法
                subject.login( new UsernamePasswordToken( user.getMobile(),user.getPassword() ));
                //获取token（sessionId）
                String id = (String) subject.getSession().getId();
                result =new FaceLoginResult( "1",id,userId );
            }
        }
        //3.修改二维码状态
        redisTemplate.boundValueOps( getCacheKey( code ) ).set( result,10,TimeUnit.MINUTES );
		return userId;
    }

	//构造缓存key
    private String getCacheKey(String code) {
        return "qrcode_" + code;
    }
}
